/**
 * LayUI tab控件扩展
 */
layui.define(['jquery', 'element', 'layer', 'yjslayer'], function (exports) {
    "use strict";

    var $ = layui.jquery
        , element = layui.element
        , layer = parent.layer === undefined ? layui.layer : parent.layer
        , yjslayer = layui.yjslayer
        , device = layui.device()
        , MOD_NAME = 'yjstab'
        , THIS_CSS = 'layui-this'
        , TabPlugin = function () {
        this.config = {
            item: '.yjs-tab-box',
            closed: true
        };
    }
        , tabItem = {};

    /**
     * 全局设置
     * @param options
     * @returns {TabPlugin}
     */
    TabPlugin.prototype.set = function (options) {
        var that = this;
        $.extend(true, that.config, options);
        return that;
    };

    /**
     * 初始化元素操作
     * @param parent
     * @returns {TabPlugin}
     */
    TabPlugin.prototype.init = function (parent) {
        var that = this
            , config = that.config
            , $container = $('' + config.item + '')
            , filter = $container.attr('lay-filter');

        // 获取父级窗口元素
        if (parent) {
            $container = $('' + config.item + '', window.parent.document);
        }

        // 检查当前层级是否成功设置lay-filter
        if (filter === undefined || filter === '') {
            $container = $('' + config.item + '', window.parent.document);
            filter = $container.attr('lay-filter');
            // 检查父级是否成功设置lay-filter
            if (filter === undefined || filter === '') {
                yjslayer.lockMsg('lay-lay-filter未设置');
            }
        }

        // 设置tab标题区域
        tabItem.titleBox = $container.children('ul.layui-tab-title');
        // 设置tab内容区域
        tabItem.contentBox = $container.children('div.layui-tab-content');
        // 设置过滤器
        tabItem.tabFilter = filter;

        return that;
    };

    /**
     * 检查当前tab是否已打开 -1：未打开；>-1：已打开；
     * @param title tab标题
     * @returns {number} 当前lay-id
     */
    TabPlugin.prototype.existed = function (title) {
        // 默认索引（未打开）
        var currentLayID = -1;

        // 判断当前tab标题区域是否已设置，未设置执行初始化
        if (tabItem.titleBox === undefined) {
            this.init();
        }

        // 验证tab标题内容，返回当前索引
        tabItem.titleBox.find('li').each(function (i, e) {
            var $cite = $(this).children('cite');
            if ($cite.text() === title) {
                currentLayID = $(this).attr('lay-id');
            }
            ;
        });

        return currentLayID;
    };

    /**
     * 内容页面特效
     * @param layID 当前tab的lay-id
     * @param isChange bool值
     */
    TabPlugin.prototype.effect = function (layID, isChange) {
        // loading动画
        var loading = layer.load(0, {
            shade: [0.5, '#FFF'] //0.5透明度的白色背景
        });

        if (isChange) {
            tabItem.contentBox.find('iframe[data-id=' + layID + ']').css({
                "opacity": "0",
                "margin-top": "50px"
            }).delay(200).animate({opacity: '1', marginTop: "0"}, 500);
            layer.close(loading);
        } else {
            tabItem.contentBox.find('iframe[data-id=' + layID + ']').parents('.layui-tab-item').addClass('layui-show');
            layer.close(loading);
        }
    };

    /**
     * 外部Tab新增
     * @param data tab对象 [title 菜单选项卡标题,href 菜单URL地址,icon 菜单的ICON图标]
     * @param refresh tab刷新标识
     */
    TabPlugin.prototype.tabAdd = function (data, refresh) {
        // 调用初始化
        $('.layui-tab-item').removeClass('layui-show');
        this.init(data.parent);

        var tab_index = this.existed(data.title),
            _this = this;

        if (tab_index === -1) {
            var layID = data.layId ? data.layId : new Date().getTime();
            var content = '<iframe src="' + data.href + '" data-id="' + layID + '" class="yjs-iframe"></iframe>';
            var title = '';
            // 添加iconfont
            if (data.icon) {
                title += '<i class="yjs-icon">' + data.icon + '</i>';
            }
            title += '<cite>' + data.title + '</cite>';

            if (this.config.closed) {
                title += '<i class="layui-icon layui-unselect layui-tab-close" data-id="' + layID + '">&#x1006;</i>';
            }

            //添加tab
            element.tabAdd(tabItem.tabFilter, {
                title: title,
                content: content,
                id: layID,
                parent: data.parent
            });

            if (data.old) {
                tabItem.titleBox.find('li[lay-id=' + layID + ']').attr("fresh", 1);
            }

            //页面淡出效果
            _this.effect(layID);

            //添加打开的菜单到列表
            data.layId = layID;
            if (!data.nodo) {
                _this.storage(data, "add");
            }

            if (this.config.closed) {
                //监听关闭事件
                tabItem.titleBox.find('li').children('i.layui-tab-close[data-id=' + layID + ']').on('click', function () {
                    element.tabDelete(tabItem.tabFilter, $(this).parent('li').attr('lay-id'), data.parent);
                    _this.tabMove(1, 1);
                    //删除数组中的对应元素
                    _this.storage(data, "close");
                    element.init();
                });
            }
            ;

            this.tabMove(tab_index, 0);
            //切换到当前打开的选项卡
            element.tabChange(tabItem.tabFilter, layID, data.parent);

            //监听鼠标右键事件
            tabItem.titleBox.find('li:not([bind])').on('contextmenu', function (event) {
                $(this).attr("bind", 1);
                var layId = $(this).attr('lay-id');
                var e = event || window.event;
                if (data.parent) {
                    $('.right-click-menu', window.parent.document).attr({
                        'lay-id': layId,
                        'parent': true
                    }).css({"top": e.pageY, "left": e.pageX, "display": "block"}).slideDown(100);
                    $('.right-click-menu', window.parent.document).find("a:not([bind])").on('click', {_this: _this}, _this.rightMenuEvent);
                } else {
                    $('.right-click-menu').attr('lay-id', layId).css({"top": e.pageY, "left": e.pageX}).slideDown(100);
                    $('.right-click-menu').find("a:not([bind])").on('click', {_this: _this}, _this.rightMenuEvent);
                }
                return false;
            });

        } else {
            element.tabChange(tabItem.tabFilter, tab_index, data.parent);
            _this.effect(tab_index, true);
            data.layId = tab_index;
            _this.storage(data, "change");

            this.tabMove(tab_index, 0);
            if (refresh) {
                _this.fresh(tab_index);
            }
        }

        $('.layui-tab-title').css('margin-left', 0);
    };

    /**
     * 右键菜单事件处理
     * @param event
     */
    TabPlugin.prototype.rightMenuEvent = function (event) {
        var _this = event.data._this;

        var event = $(this).data('event'),
            parent = $(this).parents('.right-click-menu').attr("parent");

        $(this).attr("bind", 1);

        var index = $(this).parents('.right-click-menu').attr('lay-id');

        $(this).parents('.right-click-menu').hide();

        $('.menu-list').slideUp();
        $('.tab-move-btn').find('i').html("&#xe604;");

        switch (event) {
            case "close": {
                if (index != 0) {
                    element.tabDelete(tabItem.tabFilter, index, parent);
                }
                var data = {
                    layId: index,
                    parent: parent
                }
                _this.storage(data, "close");
                break;
            }
            case "other": {
                tabItem.titleBox.find('li').each(function (i, o) {
                    var layId = $(o).attr('lay-id');
                    if (layId != index && layId != 0) {
                        element.tabDelete(tabItem.tabFilter, layId, parent);
                    }
                })
                var data = {
                    layId: index,
                    parent: parent
                }
                _this.storage(data, "other");
                break;
            }
            case "all": {
                tabItem.titleBox.find('li').each(function (i, o) {
                    var layId = $(o).attr('lay-id');
                    if (layId != 0) {
                        element.tabDelete(tabItem.tabFilter, layId, parent);
                    }
                    var data = {
                        layId: layId,
                        parent: parent
                    }
                    _this.storage(data, "all");
                })
                break;
            }
            default:
                _this.fresh(index);
        }

        _this.tabMove(1, 1);
        $(this).parents('.right-click-menu').hide();
        element.init();
    };

    /**
     * 已打开tab缓存
     * @param data
     * @param action
     */
    TabPlugin.prototype.storage = function (data, action) {
        var storage = window.sessionStorage;

        if (action == "add") {
            var _data = JSON.stringify(data);
            if (storage.menu) {
                var menulist = storage.menu;
                menulist = menulist.split("|");
                menulist.remove(_data);
                menulist.push(_data);
                var menu = menulist.join("|");
                storage.menu = menu;
            } else {
                storage.menu = _data;
            }
            storage.curMenu = _data;
        } else if (action == "all") {
            storage.removeItem("curMenu");
            storage.removeItem("menu");
        } else {
            //取得打开的菜单数组
            var menulist = storage.menu;
            if (!menulist) {
                return;
            }
            menulist = menulist.split("|");
            if (action == "close") {
                for (var index in menulist) {
                    if (index == "remove") {
                        continue;
                    }
                    if (typeof menulist[index] === 'string') {
                        var menu = JSON.parse(menulist[index]);
                    }
                    if (menu.layId == data.layId) {
                        menulist.splice(index, 1);
                    }
                }
                storage.menu = menulist.join("|");
                storage.removeItem("curMenu");
            } else {
                for (index in menulist) {
                    if (index == "remove") {
                        continue;
                    }
                    if (typeof menulist[index] === 'string') {
                        var menu = JSON.parse(menulist[index]);
                    }
                    if (menu.layId == data.layId) {
                        var _data = menulist[index];
                    }
                }
                if (action == "change") { //切换
                    storage.curMenu = _data;
                } else if (action == "other") {
                    storage.curMenu = _data;
                    storage.menu = _data;
                }
            }
        }
    };

    /**
     * 刷新当前Tab
     * @param index 当前tab的lay-id
     */
    TabPlugin.prototype.fresh = function (index) {
        element.tabChange(tabItem.tabFilter, index);
        var othis = tabItem.titleBox.find('>li[lay-id="' + index + '"]'),
            index = othis.parent().children('li').index(othis),
            parents = othis.parents('.layui-tab').eq(0),
            item = parents.children('.layui-tab-content').children('.layui-tab-item'),
            src = item.eq(index).find('iframe').attr("src");
        item.eq(index).find('iframe').attr("src", src);
    };

    /**
     * 判断Tab是否超出总宽度；
     *      超出显示左右移动Button；
     *      未超出隐藏左右移动Button；
     *
     * @param index >=0时，Tab已存在才有移动需求
     * @param scene 1：删除tab；0：切换或添加Tab
     */
    TabPlugin.prototype.tabMove = function (index, scene) {
        //取得屏幕总宽度
        var navWidth = parseInt(tabItem.titleBox.parent('div').width());
        if ($(window).width() < 450) {
            navWidth = $(window).width();
            if ($(window).width() <= 0) {
                navWidth = $(parent.window).width();
            }
        }

        //取得菜单选项卡总宽度
        var $tabNav = tabItem.titleBox.find('li'),
            tab_all_width = 0;
        $tabNav.each(function (i, n) {
            tab_all_width += $(n).outerWidth(true);
        });

        if (!$tabNav[0]) {
            return
        }
        if (tab_all_width > navWidth + 1) {
            var ml = navWidth - tab_all_width - 54;
            if (ml < 0) {
                if (index >= 0) {
                    var current_tab_left = parseInt(tabItem.titleBox.find('.' + THIS_CSS).position().left),
                        curent_tab_ml = parseInt(tabItem.titleBox.css("marginLeft")),
                        curent_ml = current_tab_left + parseInt(curent_tab_ml);

                    if (curent_ml <= 0) {
                        ml = 0 - current_tab_left;
                    } else {
                        var is_show = -(curent_tab_ml - navWidth + parseInt(tabItem.titleBox.find('.' + THIS_CSS).outerWidth(true)) + current_tab_left + 54);
                        if (is_show <= 0) {
                            ml = navWidth - current_tab_left - parseInt(tabItem.titleBox.find('.' + THIS_CSS).outerWidth(true)) - 54;
                        } else {
                            if (scene == 1 && parseInt(curent_tab_ml) < 0) {
                                ml = navWidth - current_tab_left - parseInt(tabItem.titleBox.find('.' + THIS_CSS).outerWidth(true)) - 54;
                                if (ml > 0) {
                                    ml = 0;
                                }
                            } else {
                                return;
                            }
                        }
                    }
                }
                tabItem.titleBox.css({"marginLeft": ml});
            }
            if (ml == 0 && tab_all_width < navWidth + 1) {
                tabItem.titleBox.parent('div').find('.tab-move-btn').hide();
            } else {
                if ($(window).width() > 450) {
                    tabItem.titleBox.parent('div').find('.tab-move-btn').show();
                }
            }
        } else {
            tabItem.titleBox.parent('div').find('.tab-move-btn').hide();
            tabItem.titleBox.css({"marginLeft": 0});
        }
        $('.layui-tab-title').css('margin-left', 0);
    };

    /**
     * Tab拖拽
     */
    TabPlugin.prototype.drag = function () {
        var _this = this;
        tabItem.titleBox.on("mousedown", function (e) {
            //取得屏幕总宽度
            var navWidth = parseInt(tabItem.titleBox.parent('div').width());

            //取得菜单选项卡总宽度
            var $tabNav = tabItem.titleBox.find('li'),
                tab_all_width = 0;
            $tabNav.each(function (i, n) {
                tab_all_width += $(n).outerWidth(true);
            });

            if (!$tabNav[0]) {
                return
            }
            ;

            if (tab_all_width > navWidth + 1) {
                var maxml = tab_all_width - navWidth + 54
                var _x = e.pageX - parseInt(tabItem.titleBox.css("marginLeft")); //取得鼠标到标签左边left的距离

                tabItem.titleBox.on("mousemove", function (e) {
                    var x = e.pageX - _x;
                    if (x > 0) {
                        x = 0;
                    } else if (x < -maxml) {
                        x = -maxml;
                    }
                    tabItem.titleBox.css({"marginLeft": x});
                });

                tabItem.titleBox.parents('body').on("mouseup", function (e) {
                    tabItem.titleBox.off("mousemove");
                })
                return false;
            }
        });
    };

    /**
     * Tab触碰
     */
    TabPlugin.prototype.touch = function () {
        var that = this;
        tabItem.titleBox.on("touchstart", function (e) {
            var touch = e.originalEvent.targetTouches[0] || e.originalEvent.changedTouches[0];
            //取得屏幕总宽度
            var navWidth = parseInt(tabItem.titleBox.parent('div').width());

            //取得菜单选项卡总宽度
            var $tabNav = tabItem.titleBox.find('li'),
                tab_all_width = 0;
            $tabNav.each(function (i, n) {
                tab_all_width += $(n).outerWidth(true);
            });
            if (!$tabNav[0]) {
                return
            }
            ;
            if (tab_all_width > navWidth + 1) {
                var maxml = tab_all_width - navWidth + 54
                var _x = touch.pageX - parseInt(objTab.titleBox.css("marginLeft")); //取得鼠标到标签左边left的距离

                tabItem.titleBox.on("touchmove", function (event) {
                    var move = event.originalEvent.targetTouches[0] || event.originalEvent.changedTouches[0];
                    var x = move.pageX - _x;
                    if (x > 0) {
                        x = 0;
                    } else if (x < -maxml) {
                        x = -maxml;
                    }
                    tabItem.titleBox.css({"marginLeft": x});
                });

                tabItem.titleBox.on("touchend", function (e) {
                    tabItem.titleBox.off("touchmove");
                })
            }
        });
    };

    /**
     * 根据值查找所在位置index值，查不到就返回-1
     */
    Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) return i;
        }
        return -1;
    };

    /**
     *根椐值删除元素
     */
    Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };

    /**
     * 导出插件
     */
    exports(MOD_NAME, function (options) {
        var tabPlugin = new TabPlugin();
        return tabPlugin.set(options)
    });
});